package javactxplugin.popup.actions;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;

import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import pluginGenerator.PluginCodeGenerator;
import pluginGenerator.PluginConstants;

public class GenerateCtxSemanticsAction implements IObjectActionDelegate {

	private Shell shell;
	
	
	private IJavaProject selectedProject = null;
	
	
	/**
	 * Constructor for Action1.
	 */
	public GenerateCtxSemanticsAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		
		if(selectedProject == null){
			
			MessageDialog.openInformation(
					shell,
					"JavaCtxPlugin",
					"The selection is not a Java project.");
			return;
		}
		
		
		try { /* Generate the code for the selected project */
			
			PluginCodeGenerator.generateCode(selectedProject);
			IResource r = selectedProject.getUnderlyingResource();
			r.refreshLocal(IResource.DEPTH_INFINITE, null);
			
		} catch (Exception e) {
				
				
			String msg = "An error occurred during the code generation:\n\n";
			
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
			String detail = sw.toString();

			MultiStatus info = 
				new MultiStatus(PluginConstants.PLUGIN_NAME,1, msg, null);
			info.add(new Status(IStatus.INFO, 
								PluginConstants.PLUGIN_NAME, 1, detail, null));
			ErrorDialog.openError(shell, "Time", null, info);

			e.printStackTrace();
		}
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		
		/* For the navigation in the project tree see http://www.eclipse.org/
		 * articles/Article-WorkbenchSelections/article.html */

		ITreeSelection s = (ITreeSelection)selection;
		if(s.getFirstElement() instanceof IJavaProject){
			this.selectedProject = (IJavaProject) s.getFirstElement();
		}		
	}

}






